// "use client"; // Next.JS

import { AiEditor, AiEditorOptions } from "aieditor";
import "aieditor/dist/style.css";
import { useModel } from '@umijs/max';
import { useState, forwardRef, useEffect, useRef } from "react";
import { Image } from 'antd';

export default forwardRef(function AIEditor(
  {
    placeholder,
    defaultValue,
    value,
    onChange,
    options = {},
    small,
    ...props
  },
  ref
) {
  const divRef = useRef(null);
  const aiEditorRef = useRef(null);
  const {
    initialState: { currentUser },
  } = useModel('@@initialState');

  useEffect(() => {
    const token = localStorage.getItem('TOKENES');


    const toolbarKeys = small ? {
      toolbarKeys: ["undo", "redo",
        "|", "font-size",
        "|", "link", "hr", "todo", "emoji",
        "|", "highlight", "font-color",
        "|", "bullet-list", "ordered-list", "break",
        "|", "image", "video", "code-block", "table",
        "|", "ai"
      ]
    } : {
      toolbarKeys: ["undo", "redo",
        "|", "font-size",
        "|", "bold", "italic", "underline", "strike", "link", "hr", "todo", "emoji",
        "|", "highlight", "font-color",
        "|", "align", "line-height",
        "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
        "|", "image", "video", "quote", "code-block", "table",
        "|", "printer", "fullscreen", "ai"
      ]
    }

    const image = {
      image: {
        allowBase64: true,
        defaultSize: 350,
        uploadUrl: "/apies/file/upload",
        uploadFormName: "file", //上传时的文件表单名称
        uploadHeaders: {
          'token': token,
        },
        uploaderEvent: {
          onUploadBefore: () => {
            //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
          },
          onSuccess: (file, response) => {
            //监听图片上传成功
            //注意：
            // 1、如果此方法返回 false，则图片不会被插入到编辑器
            // 2、可以在这里返回一个新的 json 给编辑器
            return {
              "errorCode": 0,
              "data": {
                "src": response?.data?.dataList?.[0]?.url,
                "alt": response?.data?.dataList?.[0]?.name
              }
            }
          },
          onFailed: () => {
            //监听图片上传失败，或者返回的 json 信息不正确
          },
          onError: () => {
            //监听图片上传错误，比如网络超时等
          },
        }
      }
    }

    const video = {
      video: {
        uploadUrl: "/apies/file/upload",
        uploadFormName: "file", //上传时的文件表单名称
        uploadHeaders: {
          'token': token,
        },
        uploaderEvent: {
          onUploadBefore: () => {
            //监听视频上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
          },
          onSuccess: (file, response) => {
            //监听视频上传成功
            //注意：
            // 1、如果此方法返回 false，则视频不会被插入到编辑器
            // 2、可以在这里返回一个新的 json 给编辑器
            return {
              "errorCode": 0,
              "data": {
                "src": response?.data?.dataList?.[0]?.url,
                "alt": response?.data?.dataList?.[0]?.name
              }
            }
          },
          onFailed: () => {
            //监听视频上传失败，或者返回的 json 信息不正确
          },
          onError: () => {
            //监听视频上传错误，比如网络超时等
          },
        }
      },
    }

    if (!divRef.current) return;
    if (!aiEditorRef.current) {

      const aiEditor = new AiEditor({
        ...toolbarKeys,
        ...image,
        ...video,
        element: divRef.current,
        placeholder: placeholder,
        content: defaultValue,
        theme: currentUser.theme,
        onChange: (ed) => {
          if (typeof onChange === "function") {
            onChange(ed.getMarkdown());
          }
        },
        ai: {
          models: {
            spark: {
              appId: "22bbaa60",
              apiKey: "248cffacf5278a468f36130321d3cf6a",
              apiSecret: "NmQ5ZGI0YTdkOTJmOTU4NTgzMjM3Mjgy",
              version: "v3.5" //支持 v2.1 v3.1 v3.5
            }
          },
          bubblePanelEnable: true,
        },
        ...options,
      });
      aiEditorRef.current = aiEditor;
    }

    return () => {
      if (aiEditorRef.current) {
        aiEditorRef.current.destroy();
        aiEditorRef.current = null;
      }
    };
  }, [currentUser.theme, small]);

  useEffect(() => {
    if (ref) {
      if (typeof ref === "function") {
        ref(divRef.current);
      } else {
        ref.current = divRef.current;
      }
    }
  }, [ref]);

  useEffect(() => {
    if (aiEditorRef.current && value !== aiEditorRef.current.getMarkdown()) {
      aiEditorRef.current.setContent(value || "");
    }
  }, [value]);

  const [preview, setpreview] = useState({
    visible: false,
  });


  const handleClick = (e) => {
    if (e.target.tagName !== 'IMG') {
      return;
    }
    let srcarr = [],
      current = 0;
    if (divRef?.current) {
      const imgTags = divRef.current.querySelectorAll('img');
      srcarr = Array.from(imgTags)?.map((el, i) => {
        if (el.src === e.target.src) {
          current = i + 1;
        }
        return el.src;
      });
    }
    setpreview((s) => ({
      current: current,
      urls: srcarr,
      visible: true,
    }));
  };


  return <div>
    <div
      style={{
        display: 'none',
      }}
    >
      <Image.PreviewGroup
        preview={{
          visible: preview?.visible,
          current: preview?.current - 1,
          onVisibleChange: (vis) =>
            setpreview((s) => ({
              ...s,
              visible: vis,
            })),
        }}
      >
        {preview?.urls?.map?.((it) => (
          <Image src={it} key={it} />
        ))}
      </Image.PreviewGroup>
    </div>
    <div onClick={handleClick} ref={divRef} {...props} />
  </div>;
});